//
//  SelectAlbumViewController.m
//  ArtDog
//
//  Created by dllo on 16/9/26.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "SelectAlbumViewController.h"
#import "BaseTableView.h"
#import <Photos/Photos.h>
#import "HLMacro.h"
#import "Masonry.h"
#import "BaseTableViewCell.h"
#import "AlbumSelectImageController.h"

@interface SelectAlbumViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) BaseTableView *tableView;

@property (nonatomic, strong) NSMutableArray *sourceArray;

@end

@implementation SelectAlbumViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNavigation];
    [self handleData];
    [self createTableView];
}

- (void)setupNavigation
{
    self.title = @"选择相册";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeAction)];
}

- (void)closeAction
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)cancelAction
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)handleData
{
    _sourceArray = [NSMutableArray array];
    PHFetchResult *albums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
    [self getAlbumFromFetchResult:albums];
    PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
    [self getAlbumFromFetchResult:smartAlbums];
}

- (void)getAlbumFromFetchResult:(PHFetchResult *)fetchResults
{
    for (NSInteger i = 0; i < fetchResults.count; i++) {
        PHCollection *collection = fetchResults[i];
        if ([collection isKindOfClass:[PHAssetCollection class]]) {
            PHAssetCollection *assetCollection = (PHAssetCollection *)collection;
            PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
            if ([assetCollection.localizedTitle isEqualToString:@"Camera Roll"]) {
                [_sourceArray addObject:@{@"相机胶卷": fetchResult}];
            } else if ([assetCollection.localizedTitle isEqualToString:@"QQ"]) {
                [_sourceArray addObject:@{@"QQ": fetchResult}];
            } else if ([assetCollection.localizedTitle isEqualToString:@"My Photo Stream"]) {
                [_sourceArray addObject:@{@"我的照片流": fetchResult}];
            }
        } else {
            NSLog(@"%@", collection);
        }
    }
}

- (void)createTableView
{
    _tableView = [[BaseTableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
}

#pragma mark - tableView delegate dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _sourceArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *pool = @"tableViewCellPool";
    BaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:pool];
    if (!cell) {
        cell = [[BaseTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:pool];
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
        cell.detailTextLabel.textColor = [UIColor lightGrayColor];
        cell.imageView.userInteractionEnabled = YES;
        cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
        cell.imageView.clipsToBounds = YES;
    }
    
    cell.textLabel.text = [_sourceArray[indexPath.row]allKeys][0];
    NSInteger count = [[_sourceArray[indexPath.row] objectForKey:cell.textLabel.text] count];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"(%ld)", count];
    if (count > 0) {
        PHAsset *asset = [_sourceArray[indexPath.row] objectForKey:cell.textLabel.text][count - 1];
        PHImageManager *imageManager = [[PHImageManager alloc]init];
        [imageManager requestImageForAsset:asset targetSize:CGSizeMake(80, 80) contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            if (result) {
                cell.imageView.image = result;
            }
        }];
    } else {
        cell.imageView.image = [UIImage imageNamed:@"placeholder"];
    }
    
    

    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AlbumSelectImageController *selectImageVC = [[AlbumSelectImageController alloc]init];
    selectImageVC.navigationItem.backBarButtonItem.title = @"选择相册";
    selectImageVC.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelAction)];
    selectImageVC.title = [_sourceArray[indexPath.row]allKeys][0];
    selectImageVC.dataArray = [_sourceArray[indexPath.row] objectForKey:selectImageVC.title];
    [self.navigationController pushViewController:selectImageVC animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
